iT邦幫忙

2024 iThome 鐵人賽

DAY 30
0
Software Development

從Servlet到Spring MVC系列 第 30

Day29 Spring MVC - Response Handling

  • 分享至 

  • xImage
  •  

0.創建module

(1) 請參考Day27 module
(2) 使用JSON相關設置
maven

 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.17.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-parameter-names -->
    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-parameter-names</artifactId>
      <version>2.17.1</version>
    </dependency>

spring-servlet.xml

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
      p:indentOutput="true"
      p:simpleDateFormat="yyyy-MM-dd"
      p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/>

一、JSON 响應

(1)@ResponseBody

前面幾天我們使用了很多這個註解,他能夠將回傳的內容不透過視圖直接响應。如果直接回傳物件它就會自動幫我們轉成JSON的形式响應,是不是很方便呢
controller

@RestController
public class JsonController {

  @ResponseBody
  @GetMapping("JsonDemo")
  public Employee JsonDemo(){
      Employee emp = new Employee("8888", "Ricky");
      return emp;
  }
}

Employee

public class Employee {
  private String empId;
  private String empName;
  //getter setter constructor toString略
}

Demo

https://ithelp.ithome.com.tw/upload/images/20241014/20128084JV2xMhHnlO.png

(2) @RestController

如果你的方法都是需返回响應體,那麼可以就可以將@Controller與@ResponseBody寫成@RestController
https://ithelp.ithome.com.tw/upload/images/20241014/201280842Q03bUNu3A.png

二、頁面跳轉

(1) Redirect

  • 跳轉不能忽略applicationContext,例如MyWebApp/
  • 可以訪問外部網址
  • 發送兩次請求

Demo

訪問redirectDemo
https://ithelp.ithome.com.tw/upload/images/20241014/20128084wZw2Wr7D8d.png
訪問redirectGoogle
https://ithelp.ithome.com.tw/upload/images/20241014/201280844oaOJNWiA3.png

(2) Forward

  • 不需要添加applicationContext
  • 不能訪問外部網址
  • 網址不變

Demo

訪問forwardDemo
https://ithelp.ithome.com.tw/upload/images/20241014/201280843sIY7jKssc.png
訪問forwardGoogle,無法訪問外部網址
https://ithelp.ithome.com.tw/upload/images/20241014/20128084wO13ZBnsyJ.png

三、靜態資源訪問

因為在web.xml中我們設定所有請求都會導向DispatcherServlet,如果沒特別為靜態資源做請求配置將會無法取得靜態資源。

範例建置

staticResourceDemo.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>staticResourceDemo</title>
</head>
<body>
    <h3>tomcat 圖片顯示:</h3>
    <img src="/static/images/tomcat.png">

</body>
</html>

public class StaticResourceController

@Controller
public class StaticResourceController {

    @GetMapping("staticResourceDemo")
    public String staticResourceDemo() {
        return "staticResourceDemo";
    }
}

放置一張圖片在路徑
https://ithelp.ithome.com.tw/upload/images/20241014/201280840WtE3xX7zq.png

Demo未配置靜態資源請求

訪問staticResourceDemo
https://ithelp.ithome.com.tw/upload/images/20241014/20128084mg54jU9Gu4.png

配置靜態資請求

springmvc-servlet.xml

<!-- static resources setting   -->
<mvc:resources mapping="/static/**" location="/static/">
    <mvc:resource-chain resource-cache="true">
        <mvc:resolvers>
            <mvc:version-resolver>
                <mvc:content-version-strategy patterns="/**"/>
            </mvc:version-resolver>
        </mvc:resolvers>
    </mvc:resource-chain>
</mvc:resources>

Demo配置靜態資源請求

訪問staticResourceDemo
https://ithelp.ithome.com.tw/upload/images/20241014/20128084PPnabtxakw.png

Reference


上一篇
Day28 Spring MVC - Request Handling (II)
下一篇
Day30 Spring MVC - FileUpload and FileDownload
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言